package com.atguigu.spzx.manager.helper;

import com.atguigu.spzx.model.entity.system.SysMenu;

import java.util.ArrayList;
import java.util.List;

public class MenuHelper {
    public static List<SysMenu> buildTree(List<SysMenu> listBefore) {
        List<SysMenu> listFamily=new ArrayList<>();

        //递归实现
        /*for (SysMenu sysMenu : listBefore) {
            if(sysMenu.getParentId()==0){
                listFamily.add(findChilder(sysMenu,listBefore));
            }
        }*/

        //非递归实现
        for (SysMenu s : listBefore) {
            s.setChildren(new ArrayList<>());
        }

        for (SysMenu sysMenu : listBefore) {
            if(sysMenu.getParentId()!=0){
                for (SysMenu menu : listBefore) {
                    if(sysMenu.getParentId()== menu.getId()){
                        menu.getChildren().add(sysMenu);
                    }
                }
            }else{
                listFamily.add(sysMenu);
            }
        }


        return listFamily;
    }

    //递归实现
    private static SysMenu findChilder(SysMenu sysMenu, List<SysMenu> listBefore) {
        List<SysMenu> result=new ArrayList<>();
        for (SysMenu menu : listBefore) {
            if(sysMenu.getId()==menu.getParentId()){
                result.add(findChilder(menu,listBefore));
            }
        }
        sysMenu.setChildren(result);
        return sysMenu;
    }
}
